import allure
from selenium.common import StaleElementReferenceException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

from page.base_page import BasePage


class OverdueDetailsReport(BasePage):
    __order_management = By.XPATH, "//*[text()='订单管理']"
    __proxy_order = By.XPATH, "//*[text()='代理订单']"
    __proxy_order_list = By.XPATH, "//*[@href = '/order/proxyOrder/proxyOrderApply']"
    __compensation_detail = By.XPATH, '//*[@href="/statistics/proxyReport/compensatoryDetails"]'
    __overdue_statistics = By.XPATH, '//*[@href="/statistics/proxyReport/overdueStatisticsProxy"]'

    def goto_proxy_order(self):
        from page.proxy_order_apply_page import ProxyOrderApply
        with allure.step('点击订单管理'):
            self.find_and_click(self.__order_management)
        with allure.step('点击代理订单'):
            self.find_and_click(self.__proxy_order)
        with allure.step('点击订单列表'):
            self.find_and_click(self.__proxy_order_list)
            self.wait(EC.visibility_of_element_located((By.XPATH, "//*[text()='借贷人姓名']")), time_out=10)
        return ProxyOrderApply(self.driver)

    def goto_compensation_detail(self):
        from page.compensation_detail_page import CompensationDetail
        with allure.step('点击代偿明细报表'):
            self.find_and_click(self.__compensation_detail)
        return CompensationDetail(self.driver)

    def goto_overdue_statistics(self):
        from page.overdue_statistics_page import OverdueStatistics
        with allure.step('点击逾期统计报表'):
            self.find_and_click(self.__overdue_statistics)
        return OverdueStatistics(self.driver)

    def get_overdue_details_summary(self):
        with allure.step("获取逾期明细汇总数据"):
            while True:
                try:
                    overdue_summary = []
                    for i in range(1, 4):
                        overdue_summary.append(
                            (self.find(By.XPATH, f"//*[@class='el-row']/div[{i}]/div").text.split(':'))[1])
                    break
                except (StaleElementReferenceException, IndexError):
                    pass
        return overdue_summary

    def get_first_overdue_details(self):
        with allure.step("获取第一条逾期记录"):
            overdue_details = []
            try:
                self.wait(EC.presence_of_element_located((By.XPATH, "//*[@class = 'el-table__body']/tbody/tr[1]")))
                for i in range(4, 13):
                    overdue_details.append(
                        self.find(By.XPATH, f"//*[@class = 'el-table__body']/tbody/tr[1]/td[{i}]").text)
            except StaleElementReferenceException:
                pass
        return overdue_details
